import { Events, Message } from './type'

export default class IframeMessage {
  constructor() {
    this.events = {}

    this.addEventListener()
  }

  private events: Events = {}

  private addEventListener() {
    window.onmessage = this.receive.bind(this)
  }

  private receive(event: Event & { data: Message }) {
    this.events[event.data.type as keyof Message] = this.events[event.data.type as keyof Message] || []

    this.events[event.data.type as keyof Message].forEach((fn: Function) => {
      fn && fn(event.data.data)
    })
  }

  public dispatch(type: string, data?: unknown, iframe?: HTMLIFrameElement) {
    if (iframe) {
      iframe.contentWindow.postMessage({ type, data }, "*")
    } else {
      window.parent.postMessage({ type, data }, "*")
    }
  }

  public on(type: string, callback: Function) {
    // this.events[type] = this.events[type] || []
    this.events[type] = [callback]

    return this
  }
}